<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/commons/global.jsp"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://libs.baidu.com/jqueryui/1.8.22/jquery-ui.min.js"></script>
    <script type="text/javascript" src="${staticPath}/static/pirobox_extended.js"></script>
    <link rel="stylesheet" href="http://www.qiepai.net/ExportHtml/css/G_1.css"/>
    <link rel="stylesheet" href="http://www.qiepai.net/ExportHtml/css/main.css"/>
    <script type="text/javascript" src="${staticPath}/static/address.js?rev=1810231915"></script>
    <link rel="stylesheet" href="${staticPath }/static/bootstrap/bootstrap.min.css">
	<script src="${staticPath }/static/bootstrap/bootstrap.min.js"></script>
	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css">
	<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
	<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/locale/bootstrap-table-zh-CN.min.js"></script>
 	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.4/css/bootstrap-dialog.min.css">
	<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.4/js/bootstrap-dialog.min.js"></script>
    <title>微信录单 第${pageIndex}页</title>
    <style>
    	input {height:22px;line-height:22px;color:blue}
    	select {height:22px;line-height:22px}
    	* {box-sizing:content-box}
    	.break_all {word-break:break-all}
    	.sku_list {width:720px;max-height:450px;overflow:auto;border-bottom:1px solid grey;margin-top:5px}
		.sku_list li {float:left;text-align:left;font-size:12px;margin-top:10px}
		.sku_list ul {border-top:1px solid grey;overflow:hidden}
		.sku_list .li1 {width:150px}
		.sku_list .li2 {width:140px}
		.sku_list .li3 {width:80px}
		.sku_list .li4 {width:80px}
		.sku_list .li5 {width:80px}
		.sku_list .li6 {width:75px}
		.sku_list .li7 {width:60px}
		.sku_list .li8 {width:30px}
		.sku_list input {color:#000;height:20px;line-height:20px}
		.sku_list .li6 input {width:65px}
		.sku_list .li7 input {width:30px}
		
		.select-res span {
			display: inline-block;
			width: 180px;
			height: 14px;
			line-height: 14px;
			padding: 7px 15px 7px 5px;
			border:solid 1px #c0c0c0;
			background: url(/haierp1/static/images/select_box_bg.gif) no-repeat 190px center;
			cursor: pointer;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
		}
		
		.select-res p {
			position: relative;
			width: 200px;
			height: 28px;
			line-height: 28px;
			border: solid 1px #c0c0c0;
			padding: 0 5px;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
			padding-right: 20px;
		}
		
		.select-res a {
			position: absolute;
			top: 0;
			right: 0;
			display: block;
			width: 28px;
			height: 28px;
			background: url(/haierp1/static/images/close_btn.jpg) no-repeat center;
			cursor: pointer;
		}
		
		.select-res input {
			width: 172px;
			height: 14px;
			line-height: 14px;
			margin-left: 4px;
			padding: 7px 5px;
			border: solid 1px #c0c0c0;
			color: #2c2c2c;
		}
		
		.select-res span.selected {
			color: #626262;
		}
		
		.select-box {
			border: solid 1px #fd8340;
			width: 536px;
			height: 450px;
			position: absolute;
			display: none;
			z-index: 5;
			background: #fff;
		}
		
		.select-box .close-btn {
			position: absolute;
			right: 5px;
			top: 5px;
			cursor: pointer;
		}
		
		.select-box .wrap {
			height: 450px;
			border: solid 1px #ddd;				
		}
		
		.select-box ul {
			float: left;
			width: 178px;
			height: 450px;
			overflow-y: scroll;
		}
		
		.select-box ul li {
			height: 25px;
			line-height: 25px;
			padding: 0 10px;
			background: url(/haierp1/static/images/arr.gif) no-repeat 152px center;
			color: #626262;
			cursor: pointer;
		}
		
		.select-box ul li.selected {
			background: url(/haierp1/static/images/arr_selected.gif) no-repeat 152px center #fd8340;
			color: #fff;
		}
    	</style>
</head>
<body style="background:#BEE1F5">
<div class="content" style="width:610px;margin:20px 10px">
    <div class="systemTip" style="margin-top:25px"><span>爱如花-订单群 第${pageIndex}页的记录</span></div>
    <div id="chat_chatmsglist" class="chatContent">
        <table width="100%" id="mytab" border="0" class="t1">
            <tr>
                <td class="page">
	                <c:forEach var="i" begin="${totalPage-20<1 ? 1 : totalPage-20}" end="${totalPage}">
	                	<c:if test="${pageIndex == i}">
	                		<span class="current">${pageIndex}</span>
	                	</c:if>
	                	<c:if test="${pageIndex != i}">
	                		<a href="/haierp1/wx/messageList?pageSize=${pageSize}&pageIndex=${i}">${i}</a>
	                	</c:if>
	                </c:forEach>
                </td>
            </tr>
        </table>
        <c:forEach items="${wxMessageItemList}" var="wxMessageItem">
        <div class="chatItem you" id="msgcontainer_${wxMessageItem.id}" <c:if test="${wxMessageItem.isSign== 1}">style="background:green"</c:if> >
            <div class="chatItemContent">
                <div class="timeyou"><span class="timeText" id="msgTime_${wxMessageItem.id}">${wxMessageItem.messageTime}</span></div>
                <div class="clear"></div>
                <c:choose>
				   <c:when test="${wxMessageItem.isSign== 1}">
				         <img id="msgcontainer_img_${wxMessageItem.id}" class="avatar" src="http://iruhua.oss-cn-hangzhou.aliyuncs.com/50_1509097655493.png"/>    
				   </c:when>
				   <c:otherwise> 
				     	<img id="msgcontainer_img_${wxMessageItem.id}" onClick="sign(${wxMessageItem.id});" class="avatar" src="http://iruhua.oss-cn-hangzhou.aliyuncs.com/50_1509097655493.png"/>
				   </c:otherwise>
				</c:choose>
                <c:choose>
				   <c:when test="${wxMessageItem.messageType== 'picture'}">  
				         <div class="cloud cloudImg">      
				   </c:when>
				   <c:otherwise> 
				     	<div class="cloud cloudText"> 
				   </c:otherwise>
				</c:choose>
                    <div class="cloudPannel">
                        <div class="cloudBody">
                            <div class="cloudContent">
                                ${wxMessageItem.fromUserName}：<br><span id="msgText_${wxMessageItem.id}">${wxMessageItem.messageContent}</span>
                            </div>
                        </div>
                        <div class="cloudArrow"></div>
                    </div>
                </div>
            </div>
        </div>
        </c:forEach>
		<table width="100%" id="mytab" border="0" class="t1">
            <tr>
                <td class="page">
	                <c:forEach var="i" begin="1" end="${totalPage}">
	                	<c:if test="${pageIndex == i}">
	                		<span class="current">${pageIndex}</span>
	                	</c:if>
	                	<c:if test="${pageIndex != i}">
	                		<a href="/haierp1/wx/messageList?pageSize=${pageSize}&pageIndex=${i}">${i}</a>
	                	</c:if>
	                </c:forEach>
                </td>
            </tr>
        </table>
    </div>
</div>
<div style="position:fixed;top:20px;left:562px">
	<ul style="color:red">
		<li onClick="prepareOrder();" style="background:#BF0A10;color:#fff;padding:5px 10px;border-radius:5px;cursor:pointer">
			生成订单
		</li>
		<li onClick="signOrder();" style="background:#BF0A10;color:#fff;padding:5px 10px;border-radius:5px;margin-top:15px;cursor:pointer">
			已录标记
		</li>
	</ul>
</div>

<div class="content" style="width:720px;position:fixed;top:0px;right:10px;margin-top:0;font-size:12px">
	<table style="border-spacing:10px;width:100%;border-collapse:separate">
		<tr>
			<td width="33%">
				<font style="color:#f04134">*</font>销　售：<select id="salesId" name="salesId">
					<option value="-1">--请选择--</option>
				</select>
			</td>
			<td width="33%">
				<font style="color:#f04134">*</font>订单时间：<input id="orderTime" name="orderTime"  type="text" style="width:125px" />
			</td>
			<td width="34%">
				<font style="color:#f04134">*</font>销售来源：<select id="platformType" name="platformType">
					<option value="-1">--请选择--</option>
					<Option value="1">有赞</Option>
                    <Option value="2" selected = "selected">微信</Option>
                    <Option value="10">其他</Option>
                    <Option value="3">微信小程序</Option>
				</select>
			</td>
		</tr>
		<tr>
			<td>
				<font style="color:#f04134">*</font>收件人：<input id="receiver" name="receiver" type="text" style="width:125px" />
			</td>
			<td>
				<font style="color:#f04134">*</font>电话号码：<input id="telephone" name="telephone" type="text" style="width:125px" />
			</td>
			<td>
				&nbsp;身份证号：<input id="idCard" name="idCard" type="text" style="width:140px" />
			</td>
		</tr>
		<tr>
			<td>
				　<font style="color:#f04134">*</font>省份：<input id="receiverState" name="receiverState" type="text" style="width:125px" />
			</td>
			<td>
				　　<font style="color:#f04134">*</font>城市：<input id="receiverCity" name="receiverCity" type="text" style="width:125px" />
			</td>
			<td>
				&nbsp;&nbsp;&nbsp;　　<font style="color:#f04134">*</font>区：<input id="receiverDistrict" name="receiverDistrict" type="text" style="width:140px" />
			</td>
		</tr>
		<tr>
			<td colspan="2">
				　<font style="color:#f04134">*</font>地址：<input id="addressDetail" name="addressDetail" type="text" style="width:373px" />
			</td>
			<td>
				&nbsp;支付方式：<select id="payType" name="payType">
				<Option value="-1">--请选择--</Option>
				<Option value="0">微信自有支付</Option>
				<Option value="1">微信代销支付</Option>
				<Option value="2">支付宝支付</Option>
				<Option value="3">银行卡支付</Option>
				<Option value="4">代付</Option>
				<Option value="5">货到付款</Option>
				<Option value="6">百度钱包支付</Option>
				<Option value="12">信用卡</Option>
			</select>
			</td>
		</tr>
		<tr>
			<td colspan="3">
				&nbsp;　备注：<input id="remark" name="remark" type="text" style="width:618px" />
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<div class="select-res">
					<span>选择省市区</span>
				</div>
				<div class="select-box">
					<div class="wrap">
						<ul class="first"></ul>
						<ul class="second"></ul>
						<ul class="third"></ul>
					</div>
				</div>
			</td>
			<td style="text-align:right">
				<a href="javascript:void(0);" style="text-decoration:underline;font-size:14px" onClick="openSkuListPanel();">添加商品</a>
			</td>
		</tr>
	</table>
	<div class="sku_list" id="skuListContainer">
		<ul style="margin-bottom:0px;line-height:28px">
			<li class="li1" style="font-size:14px;margin-top:0px">SKU代码</li>
			<li class="li2" style="font-size:14px;margin-top:0px">商品名称</li>
			<li class="li3" style="font-size:14px;margin-top:0px">商品图片</li>
			<li class="li4" style="font-size:14px;margin-top:0px">颜色</li>
			<li class="li5" style="font-size:14px;margin-top:0px">尺寸</li>
			<li class="li6" style="font-size:14px;margin-top:0px">销售价</li>
			<li class="li7" style="font-size:14px;margin-top:0px">数量</li>
			<li class="li8" style="font-size:14px;margin-top:0px">操作</li>
		</ul>
	</div>
	<div style="margin-top:10px">
		<ul>
			<li onClick="addOrder();" style="float:right;background:#49a9ee;color:#fff;padding:5px 10px;border-radius:5px;cursor:pointer;margin-right:10px">
				保存
			</li>
			<li onClick="cancelOrder();" style="float:right;background:#fff;padding:5px 10px;border-radius:5px;cursor:pointer;margin-right:20px">
				取消
			</li>
		</ul>
	</div>
</div>

<div id="skuListPanel" class="panel-body" style="display:none;width:900px;position:fixed;top:20px;right:10px;font-size:12px;padding:0px;background:#fff;padding:10px 15px 0px">
	<div class="panel panel-default">
		<div class="panel-body" style="padding:10px">
			<span style="font-size:14px">SkuCode</span>
			<input type="text" id="txt_search_departmentname" style="width:140px;color:#333" />　　
			<span style="font-size:14px">商品名称</span>
			<input type="text" id="txt_search_statu" style="width:160px;color:#333" />　　
			<span style="font-size:14px">颜色</span>
			<input type="text" id="txt_search_color" style="width:70px;color:#333" />　　
			<a href="javascript:void(0);" onClick="skuSearch();" style="font-size:14px">查询</a>　　
			<a href="javascript:void(0);" onClick="openSkuListPanel();" style="font-size:14px;color:red">取消</a>　　
     	</div>
	</div>      
	<table id="tb_departments" class="table"></table>
</div>

<div id="msgTip" style="width:300px;position:fixed;top:200px;left:50%;display:none">
	<div style="position:relative;left:-150px;padding:10px 10px;background:rgba(0, 0, 0, 0.7);border-radius:5px;color:#fff;">
		<span></span>
	</div>
</div>

<script>
var msgsObj = {};
function sign(msgId) {
	var e = $("#msgcontainer_" + msgId);
	if(msgsObj[msgId]) {
		e.css("background", "");
		delete msgsObj[msgId];
	} else {
		e.css("background", "#7fb80e");
		msgsObj[msgId] = 1;
	}
}

//手机
var regExpTel = /(1[0-9]{10})[^0-9]*/m;
//身份证号码
var regExpIdCard = /(\d{17}[0-9xX])|(\d{15})/m;
//地址json
var addressJson = {};

function prepareOrder() {
	var tel = "";
	var idCard = "";
	var recevieName = "";
	var province = "";
	var city = "";
	var district = "";
	var addrDetail = "";
	var orderTime = "";
	for(var key in msgsObj) {
		if(msgsObj[key]) {
			var text = $('#msgText_' + key).text();
			//匹配身份证
			var resIdCard = regExpIdCard.exec(text);
			if(resIdCard && (resIdCard[1] || resIdCard[2])) {
				if(resIdCard[1]) {
					idCard = resIdCard[1];
				} else {
					idCard = resIdCard[2];
				}
				text = text.replace(idCard, " ");
				orderTime = $('#msgTime_' + key).text().trim();
				//console.log("身份证：" + idCard);
			}
			//匹配手机
			var resTel = regExpTel.exec(text);
			if(resTel && resTel[1]) {
				tel = resTel[1];
				text = text.replace(tel, " ");
				orderTime = $('#msgTime_' + key).text().trim();
				//console.log("手机：" + tel);
			}
			//console.log(text);
			text = text.replace("收件人", " ");
			text = text.replace("姓名", " ");
			text = text.replace("电话", " ");
			text = text.replace("地址是", " ");
			text = text.replace("地址", " ");
			var textArr = text.split(/[^\u4e00-\u9fa5a-zA-Z0-9-]+/);
			//console.log(textArr);
			if(textArr.length > 0) {
				for(var i=0; i<textArr.length; i++) {
					var txtItem = textArr[i];
					//寻找省份
					if(province == "") {
						for(var provinceKey in addressJson) {
							var provinceKey2 = provinceKey.replace("省", "");
							var provinceKey3 = provinceKey.replace("市", "");
							if(provinceKey=='广西壮族自治区') {
								provinceKey2 = "广西省";
								provinceKey3 = "广西";
							} else if(provinceKey=='内蒙古自治区'){
								provinceKey2 = "内蒙古省";
								provinceKey3 = "内蒙古";
							} else if(provinceKey=='宁夏回族自治区') {
								provinceKey2 = "宁夏省";
								provinceKey3 = "宁夏";
							} else if(provinceKey=='西藏自治区') {
								provinceKey2 = "西藏省";
								provinceKey3 = "西藏";
							} else if(provinceKey=='新疆维吾尔自治区') {
								provinceKey2 = "新疆省";
								provinceKey3 = "新疆";
							}
							if(txtItem.search(provinceKey)==0 || txtItem.search(provinceKey2)==0 || txtItem.search(provinceKey3)==0) {
								province = provinceKey;
								if(province == "北京市") {
									city = "北京市";
								} else if(province == "上海市") {
									city = "上海市";
								} else if(province == "天津市") {
									city = "天津市";
								} else if(province == "重庆市") {
									city = "重庆市";
								}
								if(txtItem.search(provinceKey)!=-1) {
									txtItem =  txtItem.replace(provinceKey, "");
								} else if(txtItem.search(provinceKey2)!=-1) {
									txtItem =  txtItem.replace(provinceKey2, "");
								} else if(txtItem.search(provinceKey3)!=-1) {
									txtItem =  txtItem.replace(provinceKey3, "");
								}
								orderTime = $('#msgTime_' + key).text().trim();
								console.log("省：" + province);
								break;
							}
						}
					}
					//寻找市
                    if(province != "") {
                        for(var cityKey in addressJson[province]) {
                            var cityKey2 = cityKey.replace("市", "");
                            if(txtItem.search(cityKey)!=-1 || txtItem.search(cityKey2)!=-1) {
                                city = cityKey;
                                if(txtItem.search(cityKey)!=-1) {
                                    txtItem =  txtItem.replace(cityKey, "");
                                } else if(txtItem.search(cityKey2)!=-1) {
                                    txtItem =  txtItem.replace(cityKey2, "");
                                }
                                //console.log("市：" + city);
                                break;
                            }
                        }
                    }

					//寻找区
					if(city != "") {
						for(var districtKey in addressJson[province][city]) {
							if(txtItem.search(districtKey) != -1) {
								district = districtKey;
								txtItem =  txtItem.replace(district, "");
								//console.log("区：" + district);
								break;
							}
						}
					}
					txtItem = txtItem.trim();
					//寻找地址明细
					if((city!="" || district!="") && txtItem!="") {
						if(addrDetail == "") {
							addrDetail = txtItem;
							//console.log("明细地址：" + addrDetail);
						} else if(txtItem.search(/[苑|幢|楼|单元|路|坝]/)!=-1) {
							addrDetail += txtItem;
							//console.log("明细地址：" + addrDetail);
						}
					}
					//寻找姓名
					if(recevieName=="" && txtItem.length>=2 && txtItem.length<=4) {
						var firXin = txtItem.substr(0, 1);
						if("赵|钱|孙|李|周|吴|郑|王|冯|陈|楮|卫|蒋|沈|韩|杨|朱|秦|尤|许|何|吕|施|张|孔|曹|严|华|金|魏|陶|姜|戚|谢|邹|喻|柏|水|窦|章|云|苏|潘|葛|奚|范|彭|郎|鲁|韦|昌|马|苗|凤|花|方|俞|任|袁|柳|酆|鲍|史|唐|费|廉|岑|薛|雷|贺|倪|汤|滕|殷|罗|毕|郝|邬|安|常|乐|于|时|傅|皮|卞|齐|康|伍|余|元|卜|顾|孟|平|黄|和|穆|萧|尹|姚|邵|湛|汪|祁|毛|禹|狄|米|贝|明|臧|计|伏|成|戴|谈|宋|茅|庞|熊|纪|舒|屈|项|祝|董|梁|杜|阮|蓝|闽|席|季|麻|强|贾|路|娄|危|江|童|颜|郭|梅|盛|林|刁|锺|徐|丘|骆|高|夏|蔡|田|樊|胡|凌|霍|虞|万|支|柯|昝|管|卢|莫|经|房|裘|缪|干|解|应|宗|丁|宣|贲|邓|郁|单|杭|洪|包|诸|左|石|崔|吉|钮|龚|程|嵇|邢|滑|裴|陆|荣|翁|荀|羊|於|惠|甄|麹|家|封|芮|羿|储|靳|汲|邴|糜|松|井|段|富|巫|乌|焦|巴|弓|牧|隗|山|谷|车|侯|宓|蓬|全|郗|班|仰|秋|仲|伊|宫|宁|仇|栾|暴|甘|斜|厉|戎|祖|武|符|刘|景|詹|束|龙|叶|幸|司|韶|郜|黎|蓟|薄|印|宿|白|怀|蒲|邰|从|鄂|索|咸|籍|赖|卓|蔺|屠|蒙|池|乔|阴|郁|胥|能|苍|双|闻|莘|党|翟|谭|贡|劳|逄|姬|申|扶|堵|冉|宰|郦|雍|郤|璩|桑|桂|濮|牛|寿|通|边|扈|燕|冀|郏|浦|尚|农|温|别|庄|晏|柴|瞿|阎|充|慕|连|茹|习|宦|艾|鱼|容|向|古|易|慎|戈|廖|庾|终|暨|居|衡|步|都|耿|满|弘|匡|国|文|寇|广|禄|阙|东|欧|殳|沃|利|蔚|越|夔|隆|师|巩|厍|聂|晁|勾|敖|融|冷|訾|辛|阚|那|简|饶|空|曾|毋|沙|乜|养|鞠|须|丰|巢|关|蒯|相|查|后|荆|红|游|竺|权|逑|盖|益|桓|公|万俟|司马|上官|欧阳|夏侯|诸葛|闻人|东方|赫连|皇甫|尉迟|公羊|澹台|公冶|宗政|濮阳|淳于|单于|太叔|申屠|公孙|仲孙|轩辕|令狐|锺离|宇文|长孙|慕容|鲜于|闾丘|司徒|司空|丌官|司寇|仉|督|子车|颛孙|端木|巫马|公西|漆雕|乐正|壤驷|公良|拓拔|夹谷|宰父|谷梁|晋|楚|阎|法|汝|鄢|涂|钦|段干|百里|东郭|南门|呼延|归|海|羊舌|微生|岳|帅|缑|亢|况|后|有|琴|梁丘|左丘|东门|西门|商|牟|佘|佴|伯|赏|南宫|墨|哈|谯|笪|年|爱|阳|佟|第五|言|福".search(firXin) != -1) {
							recevieName = txtItem;
							//console.log("收件人：" + recevieName);
						}
					}
				}
			}
		}
	}
	
	$('#salesId').val(-1);
	$('#orderTime').val(orderTime);
	$('#platformType').val(2);
	$('#receiver').val(recevieName);
	$('#telephone').val(tel);
	$('#idCard').val(idCard);
	$('#receiverState').val(province);
	$('#receiverCity').val(city);
	$('#receiverDistrict').val(district);
	$('#addressDetail').val(addrDetail);
	$('#payType').val(-1);
	$('#remark').val('');
}

var orderSkuList = {};
/**
 * 渲染sku选择
 */
function selectSkuRend(skuObj) {
	if(orderSkuList[skuObj.skuId]) return;
	orderSkuList[skuObj.skuId] = skuObj;
	var str = "";
	str += "<ul id='skuUl_" + skuObj.skuId + "'>";
	str += "<li class='li1'>" + skuObj.skuCode + "</li>";
	str += "<li class='li2'>" + skuObj.itemName + "</li>";
	str += "<li class='li3'><img src='" + skuObj.skuPic  + "' width='60'></li>";
	if(skuObj.color) {
		str += "<li class='li4'>" + skuObj.color + "</li>";
	} else {
		str += "<li class='li4'>-</li>";
	}
	if(skuObj.scale) {
		str += "<li class='li5'>" + skuObj.scale + "</li>";
	} else {
		str += "<li class='li5'>-</li>";
	}
	str += "<li class='li6'><input id='salePrice_" + skuObj.skuId + "' name='salePrice_" + skuObj.skuId + "' type='number' value='" + skuObj.salePrice + "' /></li>";
	str += "<li class='li7'><input id='quantity_" + skuObj.skuId + "' name='quantity_" + skuObj.skuId + "' type='number' value='1' /></li>";
	str += "<li class='li8'><a href='javascript:void(0);' style='color:#49a9ee' onClick='deleteSku(" + skuObj.skuId + ");'>删除</a></li>";
	$('#skuListContainer').append(str);
	//console.log(orderSkuList);
}

/**
 * 提交订单
 */
function addOrder() {
	var errStr = "";
	if($('#salesId').val() == -1) {
		errStr += "请选择销售<br>";
	}
	if($('#orderTime').val().trim() == '') {
		errStr += "请填写订单时间<br>";
	}
	if($('#platformType').val() == -1) {
		errStr += "请选择销售来源<br>";
	}
	if($('#receiver').val().trim() == '') {
		errStr += "请填写收件人<br>";
	}
	if($('#telephone').val().trim() == '') {
		errStr += "请填写电话号码<br>";
	}
	if($('#receiverState').val().trim() == '') {
		errStr += "请填写省份<br>";
	}
	if($('#receiverCity').val().trim() == '') {
		errStr += "请填写城市<br>";
	}
	if($('#receiverDistrict').val().trim() == '') {
		errStr += "请填写区<br>";
	}
	if($('#addressDetail').val().trim() == '') {
		errStr += "请填写明细地址<br>";
	}
	if($.isEmptyObject(orderSkuList)) {
		errStr += "请添加商品<br>";
	}

    var tel = regExpTel.exec($('#telephone').val().trim());
    if(!tel||tel[1]!=tel.input) {
        errStr+="手机号不正确！<br>";
    }

    errStr+=idcardCheck($('#idCard').val().trim()).str;

	if(errStr!="") {
		$('#msgTip span').html(errStr);
		$('#msgTip').fadeIn(500).delay(1000).fadeOut(500);
		return;
	}
	
	var param = {};
	param.salesId = $('#salesId').val();
	param.salesName = $("#salesId").find("option:selected").text();
	param.orderTime = $('#orderTime').val().trim();
	param.platformType = $('#platformType').val();
	param.receiver = $('#receiver').val().trim();
	param.telephone = $('#telephone').val().trim();
	param.idCard = $('#idCard').val().trim();
	param.receiverState = $('#receiverState').val().trim();
	param.receiverCity = $('#receiverCity').val().trim();
	param.receiverDistrict = $('#receiverDistrict').val().trim();
	param.addressDetail = $('#addressDetail').val().trim();
	if($('#payType').val() != -1) {
		param.payType = $('#payType').val();
	}
	param.remark = $('#remark').val().trim();
	param.status = -2;
	//组装sku
	var outerOrderDetailList = [];
	for(var key in orderSkuList) {
		var obj = {};
		obj.skuCode = orderSkuList[key].skuCode,
		obj.skuId = orderSkuList[key].skuId,
		obj.salePrice = $('#salePrice_' + obj.skuId).val().trim();
		obj.quantity = $('#quantity_' + obj.skuId).val().trim();
		outerOrderDetailList.push(obj);
	}
	param.outerOrderDetailList = JSON.stringify(outerOrderDetailList);
	//console.log(param);
	
	$.ajax({
		type: 'POST',
		url: '/haierp1/outerOrder/add',
		data: param,
		dataType : 'json',
		success: function(res){
			//console.log(res);
			if(res.success) {
				$('#msgTip span').html("操作成功！");
				$('#msgTip').fadeIn(500).delay(1000).fadeOut(500);
				//清空订单信息
				cancelOrder();
				//标记信息
				signOrder();
			}
		}
	});
}

/**
 * 已录标记
 */
function signOrder() {
	var ids = "";
	for(var msgId in msgsObj) {
		if(msgsObj[msgId]) {
			$("#msgcontainer_" + msgId).css("background", "green");
			$("#msgcontainer_img_" + msgId).removeAttr("onclick");
			if(ids == "") {
				ids += msgId;
			} else {
				ids += "," + msgId;
			}
		}
	}
	msgsObj = {};	//重置
	if(ids != "") {
		$.ajax({
			type: 'post',
			url: '/haierp1/wx/updateWxMessageSignByIds',
			data: {'ids' : ids}
		});
	}
}

/**
 * 取消订单
 */
function cancelOrder() {
	for(var key in orderSkuList) {
		deleteSku(key);
	}
	
	$('#salesId').val(-1);
	$('#orderTime').val('');
	$('#platformType').val(2);
	$('#receiver').val('');
	$('#telephone').val('');
	$('#idCard').val('');
	$('#receiverState').val('');
	$('#receiverCity').val('');
	$('#receiverDistrict').val('');
	$('#addressDetail').val('');
	$('#payType').val(-1);
	$('#remark').val('');
	
	//console.log(orderSkuList);
}

/*
 * 选择sku
 */
function selectSku(row) {
	if(row.skuPic){
		var obj = JSON.parse(row.skuPic);
		row.skuPic = obj['picList'][0]['url'];
	}
	selectSkuRend({skuId:row.id, skuCode:row.skuCode, itemName:row.itemName, skuPic:row.skuPic, salePrice:row.salePrice, color:row.color, scale:row.scale});
	openSkuListPanel();
}

/**
 * 删除sku
 */
function deleteSku(skuId) {
	if(orderSkuList[skuId]) {
		$('#skuUl_' + skuId).remove();
		delete orderSkuList[skuId];
		//console.log(orderSkuList);
	}
}
/**
 * 校验身份证
 *
 * */
function idcardCheck(num) {
    var errstr="";
    num=num.toString();
    num = num.toUpperCase();
    if (!num) {
        return {
            str:errstr
		}
	}
    var pattern = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
    if (pattern.test(num)) {
        return {
            str:errstr
        }
    } else {
        errstr = "身份证号码不正确！";
        return {
            str:errstr
        }
	}

    //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
    /*if (! (/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
        //alert('输入的身份证号长度不对，或者号码不符合规定！\n15位号码应全为数字，18位号码末位可以为数字或X。');
        errstr="输入的身份证号长度不对，或者号码不符合规定！";
        return {
            result:false,
            str:errstr
        };
    }
    //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
    //下面分别分析出生日期和校验位
    var len, re;
    len = num.length;
    if (len == 15) {
        re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
        var arrSplit = num.match(re);

        //检查生日日期是否正确
        var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
        var bGoodDay;
        bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
        if (!bGoodDay) {
            //alert('输入的身份证号里出生日期不对！');
            errstr="输入的身份证号里出生日期不对！";
            return {
                result:false,
                str:errstr
            };
        } else {
            //将15位身份证转成18位
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;
            num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            num += arrCh[nTemp % 11];
            return {
                result:true,
                str:errstr
            };
        }
    }
    if (len == 18) {
        re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
        var arrSplit = num.match(re);

        //检查生日日期是否正确
        var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
        var bGoodDay;
        bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
        if (!bGoodDay) {
            //alert(dtmBirth.getYear());
            //alert(arrSplit[2]);
            //alert('输入的身份证号里出生日期不对！');
            errstr="输入的身份证号里出生日期不对！";
            return {
                result:false,
                str:errstr
            };
        } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var valnum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            valnum = arrCh[nTemp % 11];
            if (valnum != num.substr(17, 1)) {
                //alert('18位身份证的校验码不正确！应该为：' + valnum);
                //    errstr="18位身份证的校验码不正确！应该为："+valnum;
                errstr="身份证格式错误，请重新输入！";
                return {
                    result:false,
                    str:errstr
                };
            }
            return {
                result:true,
                str:errstr
            };
        }
    }
    errstr="输入的身份证号不对";
    return {
        result:false,
        str:errstr
    };*/
}

/*
 * 控制sku面板的显示与隐藏
 */
function openSkuListPanel() {
	$("#skuListPanel").toggle();
}

/*
 * 通过skuCode、itemName、color查询商品
 */
function skuSearch() {
	$.ajax({
    	type : "GET",
        url : "/haierp1/itemSku/queryItemSkuList",
        data : {
            skuCode : $("#txt_search_departmentname").val(),
            itemName: $("#txt_search_statu").val(),
            color   : $("#txt_search_color").val()
        },
        dataType : 'JSON',
        success : function (data) {
	        if(data.msg) {
	            var dialog = new BootstrapDialog.show({
		            title: '提示',
		            message: data.msg,
		            buttons:[{
		                label: '关闭',
		                action: function(dialog){
		                    dialog.close();
		                }
	            	}],
	        	});
	        	dialog.setSize(BootstrapDialog.SIZE_SMALL);
	        }
            $("#tb_departments").bootstrapTable('refresh');
        }
    });
	/* $("#tb_departments").bootstrapTable('refresh', {
   		url:'/haierp1/itemSku/queryItemSkuList',
   		query: {skuCode: $("#txt_search_departmentname").val(),itemName:$("#txt_search_statu").val(),color:$("#txt_search_color").val()},
   	}); */ 
}

var TableInit = function () {
    //初始化Table
    this.init = function () {
        $('#tb_departments').bootstrapTable({
            url: '/haierp1/itemSku/queryItemSkuList',
			method: 'get',                      //请求方式（*）
			pagination: true,                   //是否显示分页（*）
			height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
			pageNumber:1,                       //初始化加载第一页，默认第一页
		    pageSize: 20,                       //每页的记录行数（*）
		    sidePagination: "server",
		    queryParams: this.queryParams,//传递参数（*）
		    responseHandler:this.responseHandler,
            columns: [{
		                field: 'skuCode',
		                title: 'SKU代码',
		                width: '75px',
		                class: 'break_all'
		            }, {
		                field: 'upc',
		                title: '商品UPC',
		                width: '100px'
		            },
		            {
		                field: 'itemName',
		                title: '商品名称',
		                width: '100px'
		            }, {
		                field: 'brand',
		                title: '品牌',
		                width: '60px'
		            }, {
		                field: 'categoryName',
		                title: '所属分类',
		                width: '60px'
		            },{
		                field: 'color',
		                title: '颜色',
		                width: '60px'
		            },{
		                field: 'scale',
		                title: '尺寸',
		                width: '60px'
		            },{
		                field: 'salePrice',
		                title: '价格',
		                width: '60px'
		            },{
		                field: 'skuPic',
		                title: '图片',
		                width: '100px',
		                formatter: function(value) {
		                	if(value) {
		                		var obj = JSON.parse(value);
		                		return "<img src='" + obj['picList'][0]['url'] + "' width='80'>";
		                	}
		                }
		            },{
		                field: 'virtualInv',
		                title: '虚拟库存',
		                width: '50px'
		            },{
		                field: 'weight',
		                title: '重量(磅)',
		                width: '50px'
		            },{
		                field: "id",
		                title: '选择',
		                width: '40px',
		                formatter: function(value,row,index) {
		                	if(row.color) {
		                		row.color = row.color.replace(/\'/g, " ");
		                	}
		                	if(row.scale) {
		                		row.scale = row.scale.replace(/\'/g, " ");
		                	}
		                	if(row.brand) {
		                		row.brand = row.brand.replace(/\'/g, " ");
		                	}
		                	if(row.itemName) {
		                		row.itemName = row.itemName.replace(/\'/g, " ");
		                	}
		                	if(row.buySite) {
                                row.buySite = row.buySite.replace(/\'/g, " ");
							}
		                	return "<a href='javascript:void(0);' onclick='selectSku(" + JSON.stringify(row) + ")'>选择</a>";
		                }
		            },
		            ]
        });
    };

    //得到查询的参数
    this.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        	pageSize: params.limit,   //页面大小
            pageIndex: (params.offset/params.limit)+1,  //页码
            skuCode: $("#txt_search_departmentname").val(),
            itemName: $("#txt_search_statu").val(),
			color: $("#txt_search_color").val()
        };
        return temp;
    };
    this.responseHandler = function (res) {
    	res.rows = res.data;
    	res.total= res.totalCount;
    	return res;
    }
};

jQuery.browser={};
$(function() {
	$.ajax({
        timeout: 3000,
        async: false,
		type: "POST",
		url: "/haierp1/seller/querySellerListAll",
		dataType: "json",
		data: {
		},
		success: function (data) {
			for (var i = 0; i < data.data.length; i++) {
				$("#salesId").append("<option value="+data.data[i].id+">" + data.data[i].name + "</option>");
			}
		}
	});
	//初始化地址
	for(var i=0; i<addressArr.length; i++) {
		var provinceName = addressArr[i].value;
		var cityArr = addressArr[i].children;
		var cityJson = {};
		for(var j=0; j<cityArr.length; j++) {
			var cityName = cityArr[j].value;
			var districtArr = cityArr[j].children;
			var districtJson = {};
			for(var k=0; k<districtArr.length; k++) {
				districtJson[districtArr[k].value] = 1;
			}
			cityJson[cityName] = districtJson;
		}
		addressJson[provinceName] = cityJson;
	}
	
	//1.初始化Table
    var oTable = new TableInit();
    oTable.init();
	$(window).resize(function () {
	    $('#tb_departments').bootstrapTable('resetView');
	});
	
	jQuery.browser.msie=false;
	jQuery.browser.version=0;
	if(navigator.userAgent.match(/MSIE ([0-9]+)./)) {
		jQuery.browser.msie=true;
		jQuery.browser.version=RegExp.$1;
	}
});
</script>

<script>
var l1 = 0,l2 = 0;
var cname1, cname2, cname3;
var cid1, cid2, cid3;
var canClick = true;

//显示
$('span', $('.select-res')).on('click', function() {
	$('.select-box').toggle();
	if(canClick) {
		$('ul', $('.select-box')).html('');
		fillData();
		canClick = false;
	}
});
//选择省市区
$('ul.first', $('.select-box')).on('click', 'li', function() {
	$(this).addClass('selected').siblings().removeClass('selected');
	$('ul.third').html('');
	fillData($(this).index());
	l1 = $(this).index();
	cname1 = $(this).text();
});
$('ul.second', $('.select-box')).on('click', 'li', function() {
	$(this).addClass('selected').siblings().removeClass('selected');
	fillData(l1, $(this).index());
	l2 = $(this).index();
	cname2 = $(this).text();
});
$('ul.third', $('.select-box')).on('click', 'li', function() {
	$(this).addClass('selected').siblings().removeClass('selected');
	cname3 = $(this).text();
	$('#receiverState').val(cname1);
	$('#receiverCity').val(cname2);
	$('#receiverDistrict').val(cname3);
	$('.select-box').hide();
});

//填充级联数据
function fillData(l1, l2) {
	var temp_html = "";
	if(arguments.length == 0) {
		$.each(addressArr, function(i, pro) {
			temp_html += '<li val="' + pro.value + '">' + pro.label + '</li>';
		});
	} else if(typeof(addressArr[l1].children) != 'undefined' && arguments.length == 1) {
		$.each(addressArr[l1].children, function(i, pro) {
			temp_html += '<li val="' + pro.value + '">' + pro.label + '</li>';
		});
	} else if(typeof(addressArr[l1].children[l2].children) != 'undefined' && arguments.length == 2) {
		$.each(addressArr[l1].children[l2].children, function(i, pro) {
			temp_html += '<li val="' + pro.value + '">' + pro.label + '</li>';
		});
	}
	$('.select-box ul:eq(' + arguments.length + ')').html(temp_html);
}
</script>
</body>
</html>
